import axios, {
  type AxiosInstance,
  type AxiosRequestConfig,
  type AxiosResponse,
  type InternalAxiosRequestConfig
} from 'axios';


// 定义基础响应类型
interface BaseResponse<T = any> {
  code: number;
  data: T;
  message?: string;
}

// 扩展自定义配置
interface CustomRequestConfig extends AxiosRequestConfig {
  needToken?: boolean;  // 是否需要携带Token
}

class HttpRequest {
  private instance: AxiosInstance;

  constructor() {
    this.instance = axios.create({
      baseURL: '/api',
      timeout: 10000,
      headers: { 'Content-Type': 'application/json' }
    });

    // 请求拦截器
    this.instance.interceptors.request.use(
      (config: InternalAxiosRequestConfig) => this.handleRequest(config),
      (error) => Promise.reject(error)
    );

    // 响应拦截器
    this.instance.interceptors.response.use(
      (response: AxiosResponse) => this.handleResponse(response),
      (error) => this.handleError(error)
    );
  }

  // 处理请求: 专注于管理Token
  private handleRequest(config: InternalAxiosRequestConfig) {
    const customConfig = config as unknown as CustomRequestConfig;
    const needToken = customConfig.needToken ?? true;

    // 添加Token
    if (needToken) {
      const token = localStorage.getItem('token');
      if (token) {
        config.headers.Authorization = `Bearer ${token}`;
      } else {
        if (!window.location.pathname.includes('/login')) {
          window.location.href = '/login';
        }
        return Promise.reject(new Error('未登录'));
      }
    }

    return config;
  }

  // 处理响应: 直接返回业务数据
  private handleResponse(response: AxiosResponse): any {
    return response;
  }

  // 处理错误
  private handleError(error: any) {
    // Token过期错误
    if (error.response?.status === 401) {
      this.handleTokenExpired();
      return Promise.reject(error);
    }

    // 其他错误处理
    let errorMessage = '请求失败';
    if (error.response) {
      errorMessage = error.response.data?.message || errorMessage;
    } else if (error.request) {
      errorMessage = '网络异常，请检查连接';
    }

    console.error(errorMessage);
    return Promise.reject(error);
  }

  // Token过期处理
  private handleTokenExpired() {
    if (localStorage.getItem('token')) {
      console.error('登录已过期，请重新登录');
    }
    localStorage.removeItem('token');
    localStorage.removeItem('user');

    // 避免在登录页重定向
    if (!window.location.pathname.includes('/login')) {
      window.location.href = '/login';
    }
  }


  // 封装通用请求方法（支持泛型）
  public request<T = any>(config: CustomRequestConfig): Promise<BaseResponse<T>> {
    return this.instance.request(config);
  }

  // 封装快捷方法（GET/POST）
  public get<T = any>(url: string, params?: any, config?: CustomRequestConfig) {
    return this.request<T>({ ...config, method: 'GET', url, params });
  }

  public post<T = any>(url: string, data?: any, config?: CustomRequestConfig) {
    return this.request<T>({ ...config, method: 'POST', url, data });
  }

  // 新增 PUT/DELETE 方法
  public put<T = any>(url: string, data?: any, config?: CustomRequestConfig) {
    return this.request<T>({ ...config, method: 'PUT', url, data });
  }

  public delete<T = any>(url: string, config?: CustomRequestConfig) {
    return this.request<T>({ ...config, method: 'DELETE', url });
  }
}

const http = new HttpRequest();
export default http;